from rest_framework import serializers
from .models import DeliveryArea, DeliverymanArea, DeliveryTask, DeliveryStatusRecord
from orders.serializers import OrderSerializer
from users.serializers import UserSerializer

class DeliveryAreaSerializer(serializers.ModelSerializer):
    class Meta:
        model = DeliveryArea
        fields = ['id', 'name', 'description', 'status', 'created_at', 'updated_at']
        read_only_fields = ['created_at', 'updated_at']

class DeliverymanAreaSerializer(serializers.ModelSerializer):
    area_name = serializers.CharField(source='area.name', read_only=True)
    deliveryman_name = serializers.CharField(source='deliveryman.username', read_only=True)
    
    class Meta:
        model = DeliverymanArea
        fields = ['id', 'deliveryman', 'deliveryman_name', 'area', 'area_name', 'created_at']
        read_only_fields = ['created_at']

class DeliveryStatusRecordSerializer(serializers.ModelSerializer):
    operator_name = serializers.CharField(source='operator.username', read_only=True)
    
    class Meta:
        model = DeliveryStatusRecord
        fields = ['id', 'delivery_task', 'status', 'operator', 'operator_name', 'location', 'note', 'created_at']
        read_only_fields = ['created_at']

class DeliveryTaskSerializer(serializers.ModelSerializer):
    sales_order_detail = OrderSerializer(source='sales_order', read_only=True)
    deliveryman_name = serializers.CharField(source='deliveryman.username', read_only=True, allow_null=True)
    status_records = DeliveryStatusRecordSerializer(many=True, read_only=True)
    order_number = serializers.CharField(source='sales_order.order_number', read_only=True)
    customer_name = serializers.CharField(source='sales_order.customer.username', read_only=True)
    address = serializers.CharField(source='sales_order.address', read_only=True)
    
    class Meta:
        model = DeliveryTask
        fields = [
            'id', 'delivery_number', 'sales_order', 'sales_order_detail', 'order_number',
            'customer_name', 'address', 'deliveryman', 'deliveryman_name', 'status',
            'priority', 'estimated_delivery_time', 'actual_delivery_time', 'note',
            'status_records', 'created_at', 'updated_at', 'rejection_count'
        ]
        read_only_fields = ['delivery_number', 'created_at', 'updated_at']
    
    def create(self, validated_data):
        # 生成配送编号
        import datetime
        today = datetime.datetime.now()
        prefix = f"DEL{today.strftime('%Y%m%d')}"
        
        # 查找今天最后一个编号
        last_task = DeliveryTask.objects.filter(delivery_number__startswith=prefix).order_by('delivery_number').last()
        
        if last_task:
            last_number = int(last_task.delivery_number[len(prefix):])
            new_number = f"{prefix}{str(last_number + 1).zfill(3)}"
        else:
            new_number = f"{prefix}001"
            
        validated_data['delivery_number'] = new_number
        return super().create(validated_data)